from typing import Any, Optional

from fastapi import APIRouter, Depends, HTTPException, Response, status
from sqlalchemy import desc, and_

import models
import schemas
from libs.dependencies import Utils, UtilsObject
import requests
import json
import time

router = APIRouter()


@router.options('/query')
def option_services():
    return


@router.get('/query')
def query_env(utils: UtilsObject = Depends(Utils(False))):
    result = []
    for env in utils.db.session.query(models.Environment).all():
        result.append(env.to_dict())
    return {'code': 10000, 'msg': 'success', 'data': result}


@router.options('/list')
def option_list():
    return


@router.get('/list')
def query_list(utils: UtilsObject = Depends(Utils(False))):
    result = []
    for env in utils.db.session.query(models.Environment).all():
        result.append({'key': env.env, 'value': env.id})
    return {'code': 10000, 'msg': 'success', 'data': result}


@router.options('/save')
def option_save():
    return


@router.post('/save')
def save_env(module: schemas.SaveModel, utils: UtilsObject = Depends(Utils(False))):
    if module.dataId != '':
        env_m = utils.db.session.query(models.Environment).filter(models.Environment.id == int(module.dataId)).first()
        if not env_m:
            return {'code': 10031, 'msg': 'not found', 'data': ''}
        env_m.dbHost = module.dbHost
        env_m.dbPort = module.dbPort
        env_m.dbUser = module.dbUser
        env_m.dbPassword = module.dbPassword
        env_m.env = module.env
        env_m.xxlJob = module.xxlJob
        env_m.xxlUser = module.xxlUser
        env_m.xxlPassword = module.xxlPassword
    else:
        env_m = models.Environment(**{'env': module.env, 'dbHost': module.dbHost, 'dbPort': module.dbPort,
                                      'dbUser': module.dbUser, 'dbPassword': module.dbPassword, 'xxlJob': module.xxlJob,
                                      'xxlUser': module.xxlUser, 'xxlPassword': module.xxlPassword})
        utils.db.session.add(env_m)
    utils.db.session.commit()
    return {'code': 10000, 'msg': 'success', 'data': ''}


@router.options('/delete')
def option_delete():
    return


@router.post('/delete')
def delete_env(de: schemas.DeleteEnv, utils: UtilsObject = Depends(Utils(False))):
    if de.id != '':
        utils.db.session.query(models.Environment).filter(models.Environment.id == int(de.id)).delete()
        utils.db.session.commit()
    return {'code': 10000, 'msg': 'success', 'data': ''}
